class ProjectsController < ApplicationController
  before_filter :require_project_manager, :only =>[:new,:create,:update,:edit,:delete]
  before_filter :require_any_user, :only=>:index
  def index
      @monday=Date.today.monday
      
    if current_user.role_id==1
      @projects = Project.find :all, :order => 'status'
    else

      @projects = Project.find(:all, :conditions=>"user_id='"+String(current_user.id)+"'", :order => 'status')
                 # Project.order("status")
      #taks to add
      tasks=Task.find(:all,:conditions=>"user_id='"+String(current_user.id)+"' and percentage<100")
      tasks.each do |thisTask|
        if thisTask.start_date.to_date.monday <= @monday+6
          @projects << thisTask.project
        end
      end
      
      
      @projects=@projects.uniq
       
    end

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @projects }
    end
  end

  def show
    @project = Project.find(params[:id])
    @tasks=Task.find(:all,:conditions => 'project_id='+params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @project }
    end
  end

  def new
    @project = Project.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @project }
    end
  end


  def edit
    @project = Project.find(params[:id])
  end

  def create
    
      unless params['commit']=="Guardar"
        redirect_to( :controller => 'projects' )
        return false
      end
    
      @project = Project.new(params[:project])
      
    respond_to do |format|
      if @project.save
        format.html { redirect_to(@project, :notice => 'El proyecto fue creado con éxito.') }
        format.xml  { render :xml => @project, :status => :created, :location => @project }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @project.errors, :status => :unprocessable_entity }
      end
    end
  end

  def update

      unless params['commit']=="Guardar"
        redirect_to( :controller => 'projects' )
        return false
      end
    @project = Project.find(params[:id])

    respond_to do |format|
      if @project.update_attributes(params[:project])
        format.html { redirect_to(@project, :notice => 'El proyecto fue actualizado con éxito.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @project.errors, :status => :unprocessable_entity }
      end
    end
  end

  def destroy
    @project = Project.find(params[:id])

    @project.tasks.each{ |x|
      x.week_time_sheets.each{ |y|
        y.destroy
      }
      x.destroy
    }

    @project.destroy

    respond_to do |format|
      format.html { redirect_to(projects_url) }
      format.xml  { head :ok }
    end
  end

  def confirmation
    
    @project=Project.find(params[:id])

  end
end
